package app.modules.account.business.service;

import app.modules.account.dto.web.WebCurrentUserDTO;
import app.modules.account.dto.web.WebUserDTO;
import app.modules.account.dto.web.WebUserQueryDTO;
import app.modules.account.persistence.dao.UserDAO;
import app.modules.account.persistence.entity.UserEO;
import app.modules.security.business.service.function.IFunctionService;
import app.modules.security.dto.biz.AssignedFunctionDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jasmine.framework.common.exception.DataNotFoundException;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.CollectionUtil;
import jasmine.framework.context.CurrentSubject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author mh.z
 */
@Service
public class UserService implements IUserService {
    private final UserDAO userDAO;
    private final IFunctionService functionService;

    public UserService(UserDAO userDAO, IFunctionService functionService) {
        this.userDAO = userDAO;
        this.functionService = functionService;
    }

    /**
     * 导入数据
     *
     * @param users
     */
    @Transactional(rollbackFor = Exception.class)
    public void importUsers(List<UserEO> users) {
        CheckUtil.notNull(users, "users null");

        userDAO.saveBatch(users);
    }

    /**
     * 查询用户信息
     *
     * @param queryDTO
     * @param page
     * @return
     */
    public List<WebUserDTO> pageWebUserDTOsByCond(WebUserQueryDTO queryDTO, Page page) {
        CheckUtil.notNull(queryDTO, "queryDTO");
        CheckUtil.notNull(page, "page null");

        List<WebUserDTO> recordList = userDAO.pageWebUserDTOsByCond(queryDTO, page);

        return recordList;
    }

    /**
     * 返回当前用户信息
     *
     * @return
     */
    public WebCurrentUserDTO getCurrentUser() {
        WebCurrentUserDTO webCurrentUserDTO = new WebCurrentUserDTO();

        Long userId = CurrentSubject.getUserId();
        if (userId != null) {
            UserEO userEO = userDAO.getById(userId);

            if (userEO == null) {
                throw new DataNotFoundException(UserEO.class, userId);
            }

            List<AssignedFunctionDTO> functionList = functionService.listAssignedFunctionsByUserId(userId);
            List<String> functionCodeList = CollectionUtil.mapToList(functionList, AssignedFunctionDTO::getFunctionCode);

            webCurrentUserDTO.setUserId(userEO.getId());
            webCurrentUserDTO.setUserName(userEO.getUserName());
            webCurrentUserDTO.setUserType(userEO.getUserType());
            webCurrentUserDTO.setTenantId(userEO.getTenantId());
            webCurrentUserDTO.setPrivileges(functionCodeList);
        }

        return webCurrentUserDTO;
    }

    @Override
    public UserEO getUserById(Long id) {
        return userDAO.getById(id);
    }

}
